package com.flyco.modules.fms.controller;

import java.math.BigDecimal;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.fms.entity.FmsCategory;
import com.flyco.modules.fms.entity.FmsFeeInput;
import com.flyco.modules.fms.model.FmsFeeInputModel;
import com.flyco.modules.fms.service.IFmsCategoryService;
import com.flyco.modules.fms.service.IFmsFeeInputService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.flyco.common.system.base.controller.BaseController;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 费用录入
 * @Author: flyco
 * @Date: 2021-02-20
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "费用录入")
@RestController
@RequestMapping("/f/fms/fmsFeeInput")
public class FmsFeeInputController extends BaseController<FmsFeeInput, IFmsFeeInputService> {
    @Autowired
    private IFmsFeeInputService fmsFeeInputService;
    @Autowired
    private IFmsCategoryService fmsCategoryService;

    /**
     * 分页列表查询
     *
     * @param fmsFeeInput
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "费用录入-分页列表查询")
    @ApiOperation(value = "费用录入-分页列表查询", notes = "费用录入-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(FmsFeeInput fmsFeeInput,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<FmsFeeInput> queryWrapper = QueryGenerator.initQueryWrapper(fmsFeeInput, req.getParameterMap());
        Page<FmsFeeInput> page = new Page<FmsFeeInput>(pageNo, pageSize);
        IPage<FmsFeeInput> pageList = fmsFeeInputService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param fmsFeeInputModel
     * @return
     */
    @AutoLog(value = "费用录入-添加")
    @ApiOperation(value = "费用录入-添加", notes = "费用录入-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody FmsFeeInputModel fmsFeeInputModel) {
        if (oConvertUtils.isEmpty(fmsFeeInputModel)) {
            return Result.error("数据不存在，请检查后重试！");
        }
		FmsCategory fmsCategory = fmsCategoryService.getById(fmsFeeInputModel.getCategoryId());
		if (oConvertUtils.isEmpty(fmsCategory)) {
			return Result.error("费用科目不存在！");
		}
		if (oConvertUtils.isEmpty(fmsFeeInputModel.getSplitCount())) {
            fmsFeeInputModel.setSplitCount(1);
        }
		List<FmsFeeInput> inputList = new ArrayList<>();
        BigDecimal totalAmount = fmsFeeInputModel.getAmount();
        BigDecimal splitAmount = totalAmount.divide(new BigDecimal(fmsFeeInputModel.getSplitCount().toString()),2,BigDecimal.ROUND_HALF_UP);
        for (int i = 0; i < fmsFeeInputModel.getSplitCount(); i++) {
            FmsFeeInput fmsFeeInput = BeanUtils.instantiateClass(FmsFeeInput.class);
            BeanUtils.copyProperties(fmsFeeInputModel, fmsFeeInput);
            fmsFeeInput.setPosition(9);//后台录入的费用，仅店铺经理可以看到
            fmsFeeInput.setCategoryType(fmsCategory.getType());
            fmsFeeInput.setOccurTime(DateUtil.offsetMonth(fmsFeeInputModel.getOccurTime(),i));
            if (1 == fmsFeeInputModel.getSplitCount() - i) {
                fmsFeeInput.setAmount(totalAmount);
            } else {
                totalAmount = totalAmount.subtract(splitAmount);
                fmsFeeInput.setAmount(splitAmount);
            }
            inputList.add(fmsFeeInput);
        }
        inputList.sort((t1,t2)->t2.getOccurTime().compareTo(t1.getOccurTime()));
        fmsFeeInputService.saveBatch(inputList);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param fmsFeeInput
     * @return
     */
    @AutoLog(value = "费用录入-编辑")
    @ApiOperation(value = "费用录入-编辑", notes = "费用录入-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody FmsFeeInput fmsFeeInput) {
		FmsCategory fmsCategory = fmsCategoryService.getById(fmsFeeInput.getCategoryId());
		if (oConvertUtils.isEmpty(fmsCategory)) {
			return Result.error("费用科目不存在！");
		}
		fmsFeeInput.setCategoryType(fmsCategory.getType());
        fmsFeeInputService.updateById(fmsFeeInput);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "费用录入-通过id删除")
    @ApiOperation(value = "费用录入-通过id删除", notes = "费用录入-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        fmsFeeInputService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "费用录入-批量删除")
    @ApiOperation(value = "费用录入-批量删除", notes = "费用录入-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.fmsFeeInputService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "费用录入-通过id查询")
    @ApiOperation(value = "费用录入-通过id查询", notes = "费用录入-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        FmsFeeInput fmsFeeInput = fmsFeeInputService.getById(id);
        return Result.ok(fmsFeeInput);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param fmsFeeInput
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FmsFeeInput fmsFeeInput) {
        return super.exportXls(request, fmsFeeInput, FmsFeeInput.class, "费用录入");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FmsFeeInput.class);
    }

}
